//******************************************************************************************
// filename fastviewwidget.cpp
// implemetion file for fastviewwidget
// Last time update March 2012
//*****************************************************************************************

#include <QtGui>
#include <poppler-qt4.h>
#include <iostream>
#include "fastviewwidget.h"

FastViewWidget::FastViewWidget(QWidget *parent) : QScrollArea(parent)
{
    currentPage = -1;
    doc = 0;
    scaleFactor = 1.0;
    setAlignment(Qt::AlignCenter);
    setWidgetResizable(true);
    setMouseTracking(true);
    setStyleSheet("background: rgb(127, 127, 127)");  
}


FastViewWidget::~FastViewWidget()
{
   // delete Nothing
}

double  FastViewWidget::getDistance()
{
   return  travelDistance;
}

//show page
void FastViewWidget::showPage(int page)
{
   if(page > 0 && page < doc->numPages()+1)
   {
      if (page != -1 ){
	 currentPage = page - 1;
	 emit pageChanged(page);
	 
	 QImage image = doc->page(currentPage) ->renderToImage(scaleFactor * physicalDpiX(), scaleFactor * physicalDpiY());
	 double ratio = (double)image.width() /(double)image.height();
	 //compute size
	 int h = height();
	 int w = (int)(ratio *(double) h);
	
	 if(h != image.height())
	    image = image.scaled(w,h,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
	 // set page on to widget
	 current = new QLabel(this);
	 current->setAlignment(Qt::AlignCenter);
	 current->setPixmap(QPixmap::fromImage(image));
	 setWidget(current);
	 updateGeometry();
      }
   }
}

//set document
bool FastViewWidget::setDocument(Poppler::Document *d)
{
   // point operation 
    doc = d;
    if (doc) {
        doc->setRenderHint(Poppler::Document::Antialiasing);
        doc->setRenderHint(Poppler::Document::TextAntialiasing);
        currentPage = -1;
        setPage(1);
    }
    return doc != 0;
}

// functuion to set a page
void FastViewWidget::setPage(int page)
{
    if (page != currentPage + 1) {
       showPage(page);
    }
}


// function to handle  double click
// if a double click happen
// send a signal
void  FastViewWidget::mouseDoubleClickEvent(QMouseEvent *e)
{
   if(e->button() == Qt::LeftButton)
      emit pageClicked(currentPage+1);
}


// function to handle mouse press event
// if a middle key or right key pressed
// send a signal
void  FastViewWidget::mousePressEvent(QMouseEvent * e)
{
   if(e->button() == Qt::MidButton ||  e->button() == Qt::RightButton )
    emit midpressed();
}

// auto resize handle
void FastViewWidget::resizeEvent(QResizeEvent *e)
{
   showPage(currentPage+1);
   QScrollArea::resizeEvent(e);
}

//function to start collect data
void FastViewWidget::beginTest()
{
   startTest = true;
   travelDistance = 0.0;
   last.setX(-1);
   last.setY(-1);
}

// function to abort testing
void FastViewWidget::abortTest()
{
    startTest = false;
}
